package service;
import dao.AccountDao;
import model.Account;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
@Transactional  // 事务注解添加在类上
public class AccountServiceImpl implements AccountService {

    Logger logger = LoggerFactory.getLogger(AccountServiceImpl.class);

    @Autowired
    private AccountDao accountDao;

    @Override
    public boolean transfer(Integer fromAccountId, Integer toAccountId, double money) throws Exception {
        // 查询账户余额是否充足
        Account fromAccount = accountDao.querryAccountByID(fromAccountId);
        if (fromAccount.getBalance() < money) {
            logger.info("账户余额不足！");
            throw new Exception("账户余额不足！");
        }
        // 开始转账
        Account toAccount = accountDao.querryAccountByID(toAccountId);
        fromAccount.setBalance(fromAccount.getBalance() - money);
        toAccount.setBalance(toAccount.getBalance() + money);
        int tag1 = accountDao.updateAccount(fromAccount);
//        int i = 10 / 0;  // 模拟异常
        int tag2 = accountDao.updateAccount(toAccount);
        // 转账结果
        if (tag1 != tag2) {
            logger.info("程序异常，转账失败！");
            throw new Exception("程序异常，转账失败！");
        }
        return tag1 == tag2;
    }
}
